<?php

namespace app\admin\controller\user;

use app\admin\model\Coupon as CouponModel;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户优惠券
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * Coupon模型对象
     * @var \app\admin\model\user\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Coupon;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map = [];
            $coupon_id = $this->request->get('coupon_id');
            $user_id = $this->request->get('user_id');
            if($coupon_id){
                $map['coupon_id'] = $coupon_id;
            }
            if($user_id){
                $map['user_id'] = $user_id;
            }
            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','price','bottom_price','start_time','end_time','use_time','status','createtime']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 发放优惠券
     */
    public function send()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $user_ids = $this->request->get('user_ids');
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;

                empty($params['coupon_id']) && $this->error('请选择优惠券');
                empty($user_ids) && $this->error('请选择用户');
                $coupon = CouponModel::where('id',$params['coupon_id'])->find();
                $add_data = [];
                $start_time = time();
                $end_time = $coupon['expire_days'] > 0 ? (time()+$coupon['expire_days']*86400) : 2157591060;
                foreach (explode(',',$user_ids) as $user_id){
                    $add_data[] = [
                        'coupon_id' => $coupon['id'],
                        'user_id' => $user_id,
                        'name' => $coupon['name'],
                        'price' => $coupon['price'],
                        'bottom_price' => $coupon['bottom_price'],
                        'start_time' => $start_time,
                        'end_time' => $end_time,
                    ];
                }
                Db::startTrans();
                try {
                    $this->model->saveAll($add_data);
                    $result = true;
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}
